<template>
  <el-drawer :title="title" :visible.sync="drawer.show" :wrapperClosable="false" direction="rtl" custom-class="add-drawer"
    ref="drawer" size="30%">
    <el-form v-if="cardListForm" :rules="rules" :model="cardListForm" ref="cardFormRef" label-position="top">
      <h2 class="title_line">所属油站</h2>
      <div class="card-item">
        <el-row>
          <el-form-item label="油企名称" prop="enterpriseId">
            <el-select :disabled="!['add', 'edit'].includes(drawer.type)" @change="handleSelectChange" v-model="cardListForm.enterpriseId" placeholder="请选择油企名称" clearable
              size="small" style="width: 90%">
              <el-option v-for="item in enterpriseList" :key="item.enterpriseId" :value="item.enterpriseId"
                :label="item.enterpriseName"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="油站名称" prop="stationId">
            <el-select :disabled="!['add', 'edit'].includes(drawer.type)" v-model="cardListForm.stationId" collapse-tags multiple placeholder="请选择油站名称" clearable
              size="small" style="width: 90%">
              <el-option v-for="item in stationList" :key="item.stationId" :label="item.stationName"
                :value="item.stationId">
              </el-option>
            </el-select>
          </el-form-item>
        </el-row>
      </div>

      <h2 class="title_line">卡信息</h2>
      <div class="card-item">
        <el-row>
          <el-form-item label="卡名称" prop="physicalCardName">
            <el-input :disabled="!['add', 'edit'].includes(drawer.type)" v-model="cardListForm.physicalCardName" placeholder="请输入卡名称" clearable size="small"
              style="width: 90%" />
          </el-form-item>
          <el-form-item label="卡号" prop="physicalCardNo">
            <el-input v-model="cardListForm.physicalCardNo" disabled placeholder="请输入卡号" clearable size="small"
              style="width: 90%" />
          </el-form-item>
          <!-- <el-form-item label="秘钥" prop="icCardno">
            <el-select
              v-model="cardListForm.secret"
              placeholder="请选择秘钥"
              style="width: 90%"
              clearable
              size="small"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item label="持卡人" prop="userName">
            <el-input :disabled="!['add', 'edit'].includes(drawer.type)" maxlength="20" show-word-limit v-model="cardListForm.userName" placeholder="请输入持卡人" clearable
              size="small" style="width: 90%" />
          </el-form-item>
          <el-form-item label="手机号" prop="userPhone">
            <el-input :disabled="!['add', 'edit'].includes(drawer.type)" v-model="cardListForm.userPhone" placeholder="请输入手机号" clearable size="small" style="width: 90%" />
          </el-form-item>
          <el-form-item label="企业名称" prop="userCompany">
            <el-input :disabled="!['add', 'edit'].includes(drawer.type)" v-model="cardListForm.userCompany" placeholder="请输入企业名称" clearable size="small"
              style="width: 90%" />
          </el-form-item>
        </el-row>
      </div>

      <h2 class="title_line">{{ typeText }}</h2>
      <div class="card-item">
        <el-row>
          <template v-if="drawer.type == 'recharge'">
            <el-form-item label="充值油站选择" prop="currStationId">
            <el-select v-model="cardListForm.currStationId" placeholder="请选择充值油站名称" clearable
              size="small" style="width: 90%">
              <el-option v-for="item in currStationList" :key="item.stationId" :label="item.stationName"
                :value="item.stationId">
              </el-option>
            </el-select>
          </el-form-item>
          </template>
          <el-form-item label="面额(元)" prop="physicalCardAmount">
            <el-input disabled v-model="cardListForm.physicalCardAmount" placeholder="请输入面额"
              clearable size="small" style="width: 90%" />
          </el-form-item>
          <template v-if="drawer.type == 'consume'">
            <el-form-item label="油站名称" prop="consumptionStationId" v-if="$store.state.user.userLevel != 2">
              <el-select v-model="cardListForm.consumptionStationId" placeholder="请选择油站名称" clearable size="small"
                style="width: 90%" @change="handleChangeStaff">
                <el-option v-for="item in stationList" :key="item.stationId" :label="item.stationName"
                  :value="item.stationId">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="加油员" prop="oilPersonnelId">
              <el-select v-model="cardListForm.oilPersonnelId" placeholder="请选择加油员" clearable size="small"
                style="width: 90%" @change="handleGunList">
                <el-option v-for="item in staffList" :key="item.userId" :label="item.nickName" :value="item.userId">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="油枪名称" prop="oilGun">
              <el-select v-model="cardListForm.oilGun" placeholder="请选择油枪名称" clearable size="small" style="width: 90%">
                <el-option v-for="item in gunList" :key="item" :label="item" :value="item">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="消费金额(元)" prop="amount">
              <el-input v-model="cardListForm.amount" size="small" style="width: 90%" type="number"
              placeholder="请输入消费金额" />
            </el-form-item>
          </template>
          <template v-if="drawer.type == 'recharge'">
            <el-form-item label="充值金额(元)" prop="amount">
              <el-input v-model="cardListForm.amount" size="small" style="width: 90%" type="number" placeholder="请输入充值金额" />
            </el-form-item>
          </template>
        </el-row>
      </div>

      <!-- <div v-if="drawer.isCardReading">
        <h2 class="title_line">连接状态</h2>
        <el-form-item>
          <div class="card-item">
            <el-row>
              <div class="flex-statu">
                <el-button type="primary" plain icon="el-icon-refresh" size="mini">刷新</el-button>
                <div style="margin-left: 20px">读卡成功</div>
              </div>
            </el-row>
          </div>
        </el-form-item>
      </div> -->
    </el-form>
    <div class="drawer__footer" style="margin-bottom: 20px;">
      <el-button @click="handleClose">取 消</el-button>
      <el-button v-if="drawer.type != 'view'" type="primary" @click="handleSubmit">确定</el-button>
    </div>
  </el-drawer>
</template>
<script>
import { listEnterpriseStation } from "@/api/dept";
import { enterpriseList } from "@/api/station/order";
import {
  physicalCardAdd,
  physicalCardUpdate,
  physicalCardOrderConsumption,
  physicalCardBalanceRecharge,
  getStaffQuery,
  physicalCardOrderGetGun
} from "@/api/ic/info";
import RFIDReader from "./util/RFIDReader";
import ReaderFunction from "./util/ReaderFunction";
import { cloneDeep } from "lodash";
export default {
  props: {
    parm: {
      type: Object,
      default: null,
    },
  },
  data() {
    var validates = (rule, value, callback) => {
      if (!this.cardListForm.amount) {
          callback(new Error('输入金额不能为空'));
          return;
      }
      if (this.cardListForm.amount <= 0) {
          callback(new Error('输入金额必须大于0'));
          return;
      }
        if (Number(this.cardListForm.amount) > 1000000) {
          callback(new Error('最大数不能超过7位'));
          return;
        }
        let decimal = this.isDecimal(this.cardListForm.amount)
        if (decimal.y > 2 && decimal.x != 0) {
          callback(new Error('小数位不能大于两位'));
          return;
      }
        callback()
    }
    return {
      drawer: {
        show: this.parm ? this.parm.drawerShow : false,
        type: this.parm ? this.parm.drawerType : "read",
        isCardReading: this.parm ? this.parm.isCardReading : true,
      },
      cardListForm: this.parm ? this.parm.cardListForm : {},
      cardData: this.parm ? this.parm.cardData : {}, // 卡的参数
      enterpriseList: [],
      stationList: [],
      rules: {
        enterpriseId: [
          { required: true, message: "请选择油企", trigger: 'change' },
        ],
        stationId: [
          { required: true, message: "请选择油站", trigger: 'change' },
        ],
        userName: [
          { required: true, message: "请选择输入持卡人姓名", trigger: 'blur' },
        ],
        userPhone: [
          {
            required: true,
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
        amount: [
          { required: true, validator: validates, trigger: 'change' }
        ],
        consumptionStationId: [
          { required: true, message: "请选择消费的油站", trigger: 'change' }
        ],
        oilPersonnelId: [
          { required: true, message: "请选择消费的加油员", trigger: 'change' }
        ],
        oilGun: [
          { required: true, message: "请选择消费的油枪", trigger: 'change' }
        ]
      },
      consumeForm: {},
      staffList: [], //员工列表
      gunList: [] // 油枪列表
    };
  },
  methods: {
    isDecimal(num) {
      let data = {}
      data.x = String(num).indexOf('.') + 1;
      data.y = String(num).length - data.x;
      return data;
    },
    handleSubmit() {
      this.$refs['cardFormRef'].validate((valid) => {
        if (valid) {
          let cardListForm = cloneDeep(this.cardListForm)
          if (!cardListForm.physicalCardAmount) {
            cardListForm.physicalCardAmount = 0
          }
          if (this.$store.state.userLevel == 2) {
            cardListForm.consumptionStationId = this.$store.state.stationId
          }
          cardListForm.stationId = cardListForm.stationId.join()
          console.log(cardListForm);
          if (this.drawer.type == 'add') {
            console.log('add');
            let _this = this
            let secretKeyA = ReaderFunction.stringToHex(cardListForm.secretKeyA)
            let secretKeyB = ReaderFunction.stringToHex(cardListForm.secretKeyB)
            let physicalCardNo = ReaderFunction.stringToHex(cardListForm.physicalCardNo)
            console.log(physicalCardNo);
            let secretData = this.cardData.scretVal
            secretData = secretData.substring(12, 20)
            secretData = secretKeyA + secretData + secretKeyB
            console.log(secretData);
            // 首先调用预校验再进行下一步操作
            let validCardListForm = cloneDeep(cardListForm)
            validCardListForm.isAdd = 1
            physicalCardAdd(validCardListForm).then(res => {
              if (res && res.code === 200) {
                ReaderFunction.TyA_CS_Write2(_this.cardData.device, _this.cardData.blockNumber, _this.cardData.scretKey, physicalCardNo, async function (result) {
              console.log(result);
              if (result.retval == 0) {
                ReaderFunction.TyA_CS_Write2(_this.cardData.device, _this.cardData.blockNumber + 2, _this.cardData.scretKey, secretData, async function (result2) {
                  console.log(result2);
                  if (result2.retval == 0) {
                    RFIDReader.Sys_SetBuzzer(RFIDReader.device_id, 20, null);
                    let res = await physicalCardAdd(cardListForm)
                    _this.$message.success(res.msg);
                    _this.drawer.show = false
                    _this.$emit('getData')
                  }
                })
              } else {
                _this.$message.error('写入失败，请检查是否放置或更换实体卡')
              }
            })
              }
            })
            
          } else if (this.drawer.type == 'edit') {
            console.log('edit');
            physicalCardUpdate(cardListForm).then(res => {
              this.$message.success(res.msg);
              this.drawer.show = false
              this.$emit('getData')
            })
          } else if (this.drawer.type == 'consume') {
            console.log(cardListForm);
            let physicalCardOrderDto = (({ consumptionStationId, amount, oilGun, oilPersonnelId, physicalCardNo, }) => ({ consumptionStationId, amount, oilGun, oilPersonnelId, physicalCardNo, }))(cardListForm);
            console.log(physicalCardOrderDto);
            physicalCardOrderConsumption(physicalCardOrderDto).then(res => {
              this.$message.success(res.msg);
              this.drawer.show = false
              this.$emit('getData')
            })
          } else if (this.drawer.type == 'recharge') {
            console.log(cardListForm);
            let physicalCardBalanceDto = (({ stationId, enterpriseId, amount, physicalCardNo, currStationId }) => ({ stationId, enterpriseId, amount, physicalCardNo, currStationId }))(cardListForm);
            console.log(physicalCardBalanceDto);
            physicalCardBalanceRecharge(physicalCardBalanceDto).then(res => {
              this.$message.success(res.msg);
              this.drawer.show = false
              this.$emit('getData')
            })
          }
        }
      })
    },
    handleClose() {
      this.drawer.show = false;
    },
    // 查询员工
    handleChangeStaff(val) {
      this.staffList = []
      this.cardListForm.oilPersonnelId = null
      this.gunList = []
      this.cardListForm.oilGun = null
      getStaffQuery({ stationId: val }).then(res => {
        this.staffList = res.rows
      })
    },
    // 查询油枪
    handleGunList(val) {
      console.log(val);
      physicalCardOrderGetGun({ userId: val }).then(res => {
        console.log(res);
        this.gunList = res.data
      })
    },
    handleClearValidate() {
      this.$nextTick(() => {
        this.$refs.cardFormRef.clearValidate()
      })
    },
    // 根据油企获取油站
    handleSelectChange(value) {
      this.cardListForm.stationId = null;
      this.getStationList(value);
    },
    // 查询油企
    getEnterpriseList() {
      enterpriseList().then((res) => {
        this.enterpriseList = res.rows;
      });
    },
    getStationList(val) {
      listEnterpriseStation({ enterpriseId: val }).then((res) => {
        this.stationList = res;
      });
    },
  },
  computed: {
    title() {
      let titleTypes = {
        view: '查看',
        add: '读卡'
      };
      return titleTypes[this.drawer.type];
    },
    typeText() {
      let typeTexts = {
        view: '面额',
        add: '面额',
        consume: '消费',
        recharge: '充值'
      };
      return typeTexts[this.drawer.type];
    },
    currStationList() {
      return this.stationList.filter(f => this.cardListForm.stationId.includes(f.stationId))
    }
  },
  watch: {
    parm(newValue) {
      console.log(newValue);
      this.drawer.show = newValue.drawerShow;
      this.drawer.type = newValue.drawerType;
      this.drawer.isCardReading = newValue.isCardReading;
      this.cardListForm = newValue.cardListForm;
      this.cardData = newValue.cardData;
      if (this.cardListForm) {
        this.getStationList(newValue.cardListForm.enterpriseId)
        if (this.$store.state.user.userLevel == 2) {
          this.staffList = []
          this.cardListForm.oilPersonnelId = null
          this.gunList = []
          this.cardListForm.oilGun = null
          getStaffQuery({ stationId: this.$store.state.user.stationId }).then(res => {
            this.staffList = res.rows
          })
        }
      }
    },
  },
  created() {
    this.getEnterpriseList();
    // 如果当前是油企账号，则获取该企业下的油站
    if (this.presentEnterprise && this.presentEnterprise.enterpriseId) {
      this.getStationList(this.presentEnterprise.enterpriseId);
    }
  },
};
</script>
<style scoped lang="scss">
.flex-statu {
  display: flex;
  align-items: center;
}

.title_line {
  position: relative;
  font-size: 23px;
  margin-left: 30px;
}

.card-item {
  margin-left: 50px;
}

.title_line::after {
  content: "";
  display: block;
  position: absolute;
  height: 20px;
  width: 5px;
  top: 6px;
  left: -10px;
  background-color: rgba(242, 131, 0, 1);
}

.drawer__footer {
  text-align: end;
}

::v-deep .add-drawer {
  overflow-y: auto;
}

::v-deep .cold_btn {
  background-color: rgba(170, 170, 170, 0.5) !important;
  color: #fff !important;
  border: none !important;
}

::v-deep .destroy_btn {
  background-color: rgba(217, 0, 27, 0.5) !important;
  color: #fff !important;
  border: none !important;
}

::v-deep .destroy_active {
  background-color: rgba(217, 0, 27, 1) !important;
  color: #fff !important;
  border: none !important;
}

::v-deep .cold_active {
  background-color: rgba(170, 170, 170, 1) !important;
  color: #fff !important;
  border: none !important;
}

::v-deep .destroy_btn:hover {}
</style>
